package com.zzq.filter;


import com.zzq.domain.entity.SmilePhotographer;
import com.zzq.exception.LoginException;
import com.zzq.security.PhotographerSecurityDTO;
import com.zzq.util.JwtUtil;
import com.zzq.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.zzq.enumerate.RedisKeyEnum.SMILE_PHOTOGRAPHER_LOGIN;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");

        if (!StringUtils.hasText(token)) {

            String requestURI = request.getRequestURI();
            if (shouldSkipTokenValidation(requestURI)) {
                filterChain.doFilter(request, response);
                return;// 不进行 Token 验证，直接放行
            } else {
                throw new LoginException("无token");
            }

        }
        //解析token
        String userid = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new LoginException("token过期");
        }
        //从redis中获取用户信息

        SmilePhotographer loginUser = redisCache.getCacheObject(SMILE_PHOTOGRAPHER_LOGIN.key(userid));
        if (Objects.isNull(loginUser)) {
            throw new LoginException("redis过期");
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
    private boolean shouldSkipTokenValidation(String requestURI) {
        if (requestURI.indexOf("photographer")==-1){
            return true;
        }
        // 判断请求的路径是否是不需要验证 Token 的接口
        return requestURI.indexOf("/photographer/register")!=-1
                ||
                "/photographer/login".equals(requestURI);
    }
}
